const express = require('express');
const bodyParser = require('body-parser');
const db = require('./models/database');

const app = express();
app.use(express.static('public'));
const port = 3000;

// 中间件
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 添加根路由（首页）
app.get('/', (req, res) => {
  res.send(`
    <!DOCTYPE html>
    <html>
    <head>
      <title>仓库管理系统</title>
      <style>
        body { font-family: Arial, sans-serif; padding: 20px; }
        a { color: #0066cc; text-decoration: none; }
        li { margin: 10px 0; }
      </style>
    </head>
    <body>
      <h1>仓库管理系统</h1>
      <p>API 服务已正常运行！</p>
      <h3>可用接口：</h3>
      <ul>
        <li><a href="/products">/products</a> - 商品管理</li>
        <li><a href="/inventory">/inventory</a> - 库存管理</li>
      </ul>
    </body>
    </html>
  `);
});

// 路由
app.use('/products', require('./routes/products'));
app.use('/inventory', require('./routes/inventory'));

// 错误处理中间件（必须放在所有路由之后）
app.use((err, req, res, next) => {
  console.error('错误详情:', err.stack);
  res.status(500).json({ 
    error: '请求处理失败',
    details: process.env.NODE_ENV === 'development' ? err.message : null
  });
});

// 启动服务器
app.listen(port, () => {
    console.log(`Warehouse management system running on http://localhost:3000`);
});